<template>
	<div class="app-container">
		<div class="table-wrapper">
			<h4>供电设备易损性计算</h4>
			<el-form :inline="true" ref="queryRef" :rules="rules" label-position="right" :model="params" label-width="200px">
				<el-row justify="center">
					<el-col :span="11">
						<el-form-item label="编号：" class="form-item" prop="code">
							<el-input v-model="params.code" placeholder="" :disabled="true" clearable />
						</el-form-item>
					</el-col>
					<el-col :span="11">
						<el-form-item label="设备类型：" class="form-item" prop="equipmentType">
							<el-select v-model="params.equipmentType" multiple placeholder="请选择" clearable
								@change="onChangeEquipmentType" class="form-select" :disabled="disabled">
								<el-option v-for="item in equipmentTypeOptions" :key="item.value" :label="item.label" :value="item.value">
								</el-option>
							</el-select>
						</el-form-item>
					</el-col>
				</el-row>
				<el-row justify="center">
					<el-col :span="11">
						<el-form-item label="设防情况：" class="form-item" prop="fortification">
                            <el-select v-model="params.fortification" placeholder="请选择" class="form-select"
                                :disabled="disabled" clearable>
                                <el-option v-for="item in optionList1" :label="item.dictItemName"
                                    :value="item.dictItemCode">
                                </el-option>
                            </el-select>
                        </el-form-item>
					</el-col>
					<el-col :span="11">
						<el-form-item label="年代：" class="form-item" prop="year">
							<el-input v-model="params.year" placeholder="请输入" :disabled="disabled" clearable />
							<!-- <el-select v-model="params.years" placeholder="请选择" class="form-select" :disabled="disabled" clearable>
								<el-option v-for="item in yearsOptions" :key="item.value" :label="item.label" :value="item.value">
								</el-option>
							</el-select> -->
						</el-form-item>
					</el-col>
				</el-row>
				<el-row justify="center">
					<el-col :span="11">
						<el-form-item label="总楼层：" class="form-item" prop="floor">
							<el-input-number v-model="params.floor" placeholder="请输入" :disabled="disabled" clearable />
						</el-form-item>
					</el-col>
					<el-col :span="11"></el-col>
				</el-row>
				<!-- <el-row justify="center">
					<el-col :span="11">
						<el-form-item label="维护人：" class="form-item" prop="userName">
							<el-input v-model="params.userName" placeholder="" clearable />
						</el-form-item>
					</el-col>
					<el-col :span="11">
						<el-form-item label="总楼层：" class="form-item" prop="floor">
							<el-input-number v-model="params.floor" placeholder="请输入" :disabled="disabled" clearable />
						</el-form-item>
					</el-col>
				</el-row>
				<el-row justify="center">
					<el-col :span="11">
						<el-form-item label="维护人所属单位：" class="form-item" prop="maintainerUnit">
							<el-input v-model="params.maintainerUnit" placeholder="" clearable />
						</el-form-item>
					</el-col>
					<el-col :span="11">
						<el-form-item label="维护时间：" class="form-item" prop="createTime">
							<el-date-picker v-model="params.createTime" type="date" value-format="YYYY-MM-DD" placeholder="选择日期">
							</el-date-picker>
						</el-form-item>
					</el-col>
				</el-row> -->
			</el-form>
			
			<el-form :inline="true" ref="table1FormRef" :rules="rules" label-position="right" :model="tableData"
				style="margin:20px 0;" @submit.prevent>
				<h4>表1 高压电气设备破坏概率的正太分布曲线参数值</h4>
				<el-table :data="tableData" border style="width: 100%">
					<el-table-column prop="equipmentType" label="设备类型" width="400"></el-table-column>
					<el-table-column prop="u" label="μ"></el-table-column>
					<el-table-column prop="o" label="σ"></el-table-column>
					<!-- <el-table-column prop="u" label="μ" width="200"></el-table-column>
					<el-table-column prop="o" label="σ" width="200"></el-table-column>
					<el-table-column prop="floor" label="设备所在楼层">
						<template #default="{ row, $index }">
							<el-form-item :prop="`${$index}.floor`" :rules="rules.floor">
								展示楼层
								<template v-if="!isAdd">{{ row.floor }}</template>
								可编辑楼层
								<div v-else class="input-floor">
									<template v-if="row.floor && row.floor.length">
										<el-tag v-for="tag in row.floor.split(',')" :key="tag" effect="dark" type="success"
											:disable-transitions="false" closable @close="handleClose(row, tag)">
											{{ tag }}
										</el-tag>
									</template>
									<template v-if="row.inputVisible">
										<el-input-number ref="InputRef" v-model="row.inputValue" size="small" clearable placeholder="回车确定" @keyup.enter="handleInputConfirm(row)" />
										<el-button v-if="row.inputVisible" type="primary" size="small" @click="handleInputConfirm(row)">确定</el-button>
										<el-button v-if="row.inputVisible" type="warning" size="small" @click="row.inputVisible = false;">取消</el-button>
									</template>
									<el-button v-else type="primary" size="small" @click="row.inputVisible = true;">
										<el-icon>
											<Plus />
										</el-icon>
									</el-button>
								</div>
							</el-form-item>
						</template>
					</el-table-column> -->
				</el-table>
			</el-form>

			<el-form :inline="true" ref="table2FormRef" :rules="rules" label-position="right" :model="tableData2">
				<el-row v-if="isAdd" justify="end">
					<el-form-item class="bottom-button">
						<el-button type="primary" @click="onCalc">计算</el-button>
						<el-button type="primary" @click="onSubmit">提交</el-button>
					</el-form-item>
				</el-row>
				<el-table class="listTable" ref="multipleTableRef" border :data="tableData2" :span-method="objectSpanMethod"
					style="width: 100%" :cell-style="{ border: '1px solid #e5ebf7', }"
					:header-cell-style="{ border: '1px solid #e5ebf7', borderLeft: 'none' }">
					<el-table-column prop="equipmentType" header-align="center" align="center" label="设备类型" />
					<!-- <el-table-column prop="floor" header-align="center" align="center" label="设备所在楼层" width="120" /> -->
					<el-table-column header-align="center" align="center" label="设备所在楼层">
                        <template #default="{ row, $index }">
                            <el-form-item :prop="`tableData2.${$index}.floor`">
                                <el-input v-model="row.floor" :disabled="row.disabled" size="small" @change="onChangeFloor(row, $index)"></el-input>
                            </el-form-item>
                        </template>
                    </el-table-column>
					<el-table-column prop="intensity" header-align="center" align="center" label="烈度（X）" />
					<el-table-column prop="u" header-align="center" align="center" label="μ" />
					<el-table-column prop="o" header-align="center" align="center" label="σ" />
					<el-table-column prop="erf" header-align="center" align="center" width="300">
						<template #header>
							<!-- 公式 -->
							<MultilineFormula display="block" tagOffset="-6px" font-size="16px" style="padding: 5px 0;" :option="[
								{ content: 'erf' },
								{ content: '(x)' },
								{ content: '=' },
								{
									rows: [
										[{ content: '2' }],
										[

											{ content: '√' },
											{ content: '—', top: '-5px', left: '-7px' },
											{ content: 'π', top: '2px', left: '-22px' },
										]
									]
								},

								{ content: '∫', scale: 1.5, topContent: 'x', bottomContent: '0' },
								{ content: 'e', super: '-t2', },

								{ content: 'dt' },
							]">
							</MultilineFormula>
						</template>
					</el-table-column>
					<el-table-column prop="fxerf" header-align="center" align="center" width="300">
						<template #header>
							<!-- 公式 -->
							<MultilineFormula display="block" tagOffset="-6px" font-size="16px" style="padding: 5pc 0;" :option="[
								{ content: 'F' },
								{ content: '(x)' },
								{ content: '=' },
								{ content: '0.5+' },
								{ content: '0.5', sub: 'erf' },
								{ content: '(' },
								{
									rows: [
										[{ content: '(x-μ)' }],
										[
											{ content: 'σ' },
											{ content: '√' },
											{ content: '—', top: '-5px', left: '-6px' },
											{ content: '2', top: '2px', left: '-15px' },
										]
									]
								},
								{ content: ')' },
							]">
							</MultilineFormula>
						</template>
					</el-table-column>
					<el-table-column prop="fxexp" header-align="center" align="center" width="350">
						<template #header>
							<!-- 公式 -->
							<MultilineFormula display="block" tagOffset="-6px" font-size="16px" style="padding: 5pc 0;" :option="[
								{ content: 'f' },
								{ content: '(x)' },
								{ content: '=' },
								{
									rows: [
										[{ content: '1' }],
										[
											{ content: 'σ' },
											{ content: '√' },
											{ content: '—', top: '-5px', left: '-7px' },
											{ content: '2π', top: '2px', left: '-15px' },
										]
									]
								},
								{ content: 'exp' },
								{ content: '[' },
								{ content: '-' },
								{
									rows: [
										[{ content: '(x-μ)', super: '2', }],
										[
											{ content: '2σ', super: '2', }
										]
									]
								},
								{ content: ']' },
							]">
							</MultilineFormula>
						</template>
					</el-table-column>
					<el-table-column header-align="center" align="center" label="修正值">
						<template #default="scope">
							<el-form-item :prop="`tableData2.${scope.$index}.fxexpCorrect`" :rules="rules.fxexpCorrect">
								<el-input v-model="scope.row.fxexpCorrect" :disabled="scope.row.disabled" size="small"></el-input>
							</el-form-item>
						</template>
					</el-table-column>
				</el-table>
			</el-form>

			<el-row justify="end">
				<el-button type="primary" style="margin:20px 0;" @click="buildChartLine">生成曲线</el-button>
			</el-row>
			<!-- echarts图表 -->
			<div v-if="showChart">
				<h4>设备破坏率均值-烈度关系曲线</h4>
				<el-row :gutter="20">
					<el-col :span="8" v-if="tableData.some(item=>item.equipmentType.includes('变压器'))">
						<div class="myChart byq" style="width: 100%;height:400px;"></div>
					</el-col>
						<el-col :span="8" v-if="tableData.some(item=>item.equipmentType.includes('断路器'))">
						<div class="myChart dlq" style="width: 100%;height:400px;"></div>
					</el-col>
					<el-col :span="8" v-if="tableData.some(item=>item.equipmentType.includes('隔离开关'))">
						<div class="myChart glkg" style="width: 100%;height:400px;"></div>
					</el-col>
					<el-col :span="8" v-if="tableData.some(item=>item.equipmentType.includes('避雷器'))">
						<div class="myChart blq" style="width: 100%;height:400px;"></div>
					</el-col>
					<el-col :span="8" v-if="tableData.some(item=>item.equipmentType.includes('电流互感器'))">
						<div class="myChart dlhgq" style="width: 100%;height:400px;"></div>
					</el-col>
					<el-col :span="8"  v-if="tableData.some(item=>item.equipmentType.includes('电压互感器'))">
						<div class="myChart dyhgq" style="width: 100%;height:400px;"></div>
					</el-col>
				</el-row>

				<h4 style="margin-top: 50px;">各类设备破坏概率的拟合曲线对比及概率密度分布曲线对比如图二和图三所示</h4>
				<el-row :gutter="20">
					<el-col :span="12">
						<div class="myChart p2" style="width: 100%;height:550px;"></div>
					</el-col>
					<el-col :span="12">
						<div class="myChart p3" style="width: 100%;height:550px;"></div>
					</el-col>
				</el-row>
			</div>
		</div>
	</div>
</template>

<script setup>
import { reactive, toRefs, ref, watch } from "vue";
// 引入接口
import { getInfo } from '@/api/login';
import {
	getByIdAndType, //查询信息
	generateCurve, //生成曲线
	caPseVulnerability, //计算
	savePseVulnerability, //保存
} from "@/api/lifelineVulnerAnalysis/lifelineVulnerAnalysis.js";
import { getValidDictItemsByDictCode } from "@/api/map/disasterDataManagement/lifelineSystemInfo.js";
// 引入公用方法
import { parseTime } from "@/utils/ruoyi.js";
// 引入store
import useUserStore from '@/store/modules/user';
import useDictStore from '@/store/modules/dict';
// 引入公式组件
import Formula from '@/components/Formula';
import MultilineFormula from '@/components/Formula/multiline';
// 引入图表v5.4.2
// import '@/utils/echarts-v5.4.2/echarts.min.js';
// const echarts = window.echarts;
import * as echarts from '@/utils/echarts-v5.4.2/echarts.esm.min.js';
// 引入图表数据处理
import ecStat from 'echarts-stat';

// 获取pinia
const userStore = useUserStore();
const dictStore = useDictStore();
// 用户名
const userName = computed(() => userStore.name || '');
// 所属机构名称
const orgName = computed(() => userStore.orgName || '');

// 当前对象实例
const { proxy } = getCurrentInstance();
// 当前路由
const route = useRoute();
const router = useRouter();
// 打开类型，query为查看
let operateType = computed(() => route.query.operateType || false);
// 是否是新增页，有路由参数是详情页，否则是新增页
let isAdd = computed(() => (route.query.id && route.query.operateType ? false : true));
// 是否禁用
const disabled = ref(false);

// 最多保留N小数 ,N 在 options {decimals: N} 中定义
const positivedecimals = (rule, value, callback) => {
	value = String(value);
	if (
		value.indexOf(".") != -1 &&
		(value.split(".").length > rule.options.decimals ||
			value.split(".")[0] === "" ||
			value.split(".")[1] === "")
	) {
		callback(new Error()); //防止输入多个小数点
	} else if (
		value.indexOf(".") != -1 &&
		value.split(".")[1].length > rule.options.decimals
	) {
		callback(new Error()); //小数点后两位
	} else {
		callback();
	}
};
//验证是否yyyy年份（非必填）
const isYearNotMust = (rule, value, callback) => {
	if (value == '' || value == undefined || value == null) {
		callback(new Error('请输入yyyy格式如2022'));
	} else if (isNaN(Number(value))) {
		callback(new Error('请输入yyyy格式如2022'));
	} else if (value.toString().length != 4) {
		callback(new Error('请输入yyyy格式如2022'));
	} else if (value.toString().indexOf(".") != -1) {
		callback(new Error('请输入yyyy格式如2022'));
	} else {
		callback();
	}
}
// 表格
const multipleTableRef = ref();
const arrTable = [
	{
		equipmentType: '变压器',
		u: '7.88',
		o: '1.14',
		floor: '',
	},
	{
		equipmentType: '断路器',
		u: '8.95',
		o: '1.11',
		floor: '',
	},
	{
		equipmentType: '隔离开关',
		u: '9.60',
		o: '1.36',
		floor: '',
	},
	{
		equipmentType: '避雷器',
		u: '9.21',
		o: '1.28',
		floor: '',
	},
	{
		equipmentType: '电流互感器',
		u: '9.50',
		o: '1.48',
		floor: '',
	},
	{
		equipmentType: '电压互感器',
		u: '9.41',
		o: '1.44',
		floor: '',
	}
];
// 烈度
const arrIntensity = [6, 7, 8, 9, 10];

const data = reactive({
	// 表单参数
	params: {
		code: "",//编号
		equipmentType: [],//设备类型""
		year: "",//年代
		fortification: "", //设防情况
		createTime: parseTime(new Date()), //维护时间
		userName: userName.value, //维护人
		maintainerUnit: orgName.value, //维护人所属单位
		floor: undefined,//总楼层
	},
	// 设备类型
	equipmentTypeOptions: [
		//候选值：变压器、断路器、隔离开关、避雷器、电流互感器、电压互感器
		{
			value: '变压器',
			label: '变压器'
		}, {
			value: '断路器',
			label: '断路器'
		}, {
			value: '隔离开关',
			label: '隔离开关'
		}, {
			value: '避雷器',
			label: '避雷器'
		}, {
			value: '电流互感器',
			label: '电流互感器'
		}, {
			value: '电压互感器',
			label: '电压互感器'
		}
	],
	// 设防情况
	fortificationOptions: dictStore.fortificationOptions || [],
	// 年份
	yearsOptions: dictStore.yearsOptions1 || [],
	// 表单验证规则
	rules: {
		// code: [
		//     { required: true, message: '', trigger: 'blur' },
		// ],
		fortification: [
			{ required: true, message: '请选择', trigger: 'change' }
		],
		year: [
            {
                required: true,
                message: "请输入正确数值",
                validator: isYearNotMust,
                trigger: ["change", "blur"],
            }
        ],
		equipmentType: [
			{ required: true, message: '请选择', trigger: 'change' }
		],
		floor: [
			{ required: true, message: '请输入', trigger: 'change' },
		],
		fxexpCorrect: [
			{ required: true, message: "请输入", trigger: "blur" },
			{
				message: "请输入正确数值，最多保留四位小数",
				validator: positivedecimals,
				options: { decimals: 4 },
				trigger: ["change", "blur"],
			},
		],
	},
	// 表格数据,深拷贝保留原有数据
	tableData: JSON.parse(JSON.stringify(arrTable)),
	tableData2: [
		// {
		// 	equipmentType: '变压器', // 设备类型
		// 	intensity: '6', // 区间
		// 	u: '7.88',
		// 	o: '1.14',
		// 	erf: '', //erf
		// 	fxerf: '', //fxerf
		// 	fxexp: '', //fxexp
		// 	fxexpCorrect: '', //修正值
		// 	floor: '', //所在楼层
		// },
	],
});
const {
	params,
	fortificationOptions,
	yearsOptions,
	equipmentTypeOptions,
	rules,
	tableData,
	tableData2,
} = toRefs(data);

// 设备类型选择事件
function onChangeEquipmentType(val) {
	if (val) {
		// 先从原始数据获取
		let arr = arrTable.filter(item1 => val.includes(item1.equipmentType))
		arr.map(item1 => {
			//选择类型在原有表格中则进行覆盖,保证之前的设置不丢失
			const obj = tableData.value.find(item => item1.equipmentType == item.equipmentType);
			// 保证变量内存地址不变并修改值
			Object.assign(item1, obj);
		});
		tableData.value = arr;
	}
}

// 根据表1的数据设置表2
function setTableData2BytableData(data) {
	const arr = [];
	// 遍历设备类型
	data.map(item => {
		if (item.floor) {
			item.floor.split(',').map(itemFloor => {
				// 遍历烈度
				arrIntensity.map(itemIntensity => {
					arr.push({
						...item,
						// 楼层
						floor: itemFloor,
						// 烈度
						intensity: itemIntensity,
					});
				})
			})
		} else {
			// 遍历烈度
			arrIntensity.map(itemIntensity => {
				arr.push({
					...item,
					// 楼层
					floor: '',
					// 烈度
					intensity: itemIntensity,
				});
			})
		}
	})
	tableData2.value = arr;
}

// 设备所在楼层
// 输入设备楼层号事件
function onChangeFloor(row, index) {
	if(row.floor > (params.value.floor||0)){
		proxy.$modal.msgWarning('设备所在楼层不能大于总楼层数！');
		row.floor = null;
	} else {
		for (let i = 0; i < 5; i++) {
			tableData2.value[index + i].floor = row.floor;
		}
	}
}
// 输入框确认事件
function handleInputConfirm(row) {
	if(!params.value.floor) {
		proxy.$modal.msgWarning("请设置总楼层数!");
		return false;
	} else {
		if(row.inputValue > params.value.floor) {
			proxy.$modal.msgWarning("输入楼层号不能大于总楼层数!");
		}
		else if (row.floor.split(',').includes(row.inputValue + '')) {
			proxy.$modal.msgWarning("当前楼层已存在,请输入其它楼层号!");
		} else {
			if (!row.floor) {
				row.floor += row.inputValue;
			} else {
				row.floor += ',' + row.inputValue;
			}
			row.inputVisible = false;
		}
	}
}
// 删除楼层事件
function handleClose(row, tag) {
	if (row && row.floor) {
		const arrFloor = row.floor.split(',');
		const index = arrFloor.indexOf(tag);
		if (index > -1) {
			arrFloor.splice(index, 1);
			row.floor = arrFloor.join(',');
		}
	}
}

// 设置图表参数
function setChartOptions(data, titleName, type) {
	const xAxisData = Object.keys(data.threadMap[type]);
	const scatterData = Object.values(data.dropMap[type]);
	const lineData = Object.values(data.threadMap[type]);
	// 设置数据
	const arrData = [];
	if(xAxisData && xAxisData.length) {
		xAxisData.map((item, index) => {
			arrData.push([Number(item), scatterData[index]||'']);
		});
	}
	// See https://github.com/ecomfe/echarts-stat
	echarts.registerTransform(ecStat.transform.regression);
	return {
		dataset: [
			{
				source: arrData
			},
			{
				transform: {
					type: 'ecStat:regression',
					// echarts四种回归算法类型：'linear'（线性回归）、'exponential'（指数回归）、'logarithmic'（对数回归）、'polynomial'（多项式回归）
					config: {
						// method: 'logarithmic', //对数回归
						method: 'polynomial',  //多项式回归
						order: 3, //多项式阶数
					}
				}
			}
		],
		title: {
			bottom: 0,
			left: 'center',
			text: titleName||'',
			textStyle: {
				fontWeight: 'normal',
				fontSize: 18
			}
		},
		legend: {},
		color: ['#000000', '#ff0000'],
		tooltip: {
			trigger: 'axis',
			axisPointer: {
				type: 'cross'
			}
		},
		xAxis: {
			name: '烈度',
			type: 'value',
			// data: xAxisData,
			// 是否脱离0值比例
			scale: true,
			min: 6,
			max: 11,
		},
		yAxis: {
			name: '破坏概率',
			min: 0,
			splitLine: {
				lineStyle: {
					type: 'dashed'
				}
			},
			// // 最小、大间隔
			// minInterval: 0.0001,
			// maxInterval: 1,
			// interval: 0.05,
			// // 对数轴的底数
			// logBase: 10,
		},
		series: [
			{
				name: '样本',
				type: 'scatter',
				// data: scatterData,
				// 数据点
				symbolSize: 5,
				symbol: 'circle',
				datasetIndex: 0,
			}, {
				name: '拟合曲线',
				// data: lineData,
				type: 'line',
				// 开启平滑处理
				smooth: true,
				// 数据点
				symbolSize: 0.1,
				symbol: 'circle',
				datasetIndex: 1,
				label: { show: true, fontSize: 16 },
				labelLayout: { dx: -20 },
				encode: { label: 2, tooltip: 1 }
			}
		]
	};
}
//变压器
let m_chartBYQ = null
const buildChartBYQ = (data) => {
	if (!m_chartBYQ) {
		m_chartBYQ = echarts.init(document.querySelector('.byq'));
	}
	if(!data) {
		proxy.$modal.msgWarning('没有变压器曲线数据，不能生成曲线！');
	}
	// 设置图表参数
	const option = setChartOptions(data, '(a)变压器', 'BYQ');
	m_chartBYQ.clear();
	m_chartBYQ.setOption(option, true);
}
//断路器
let m_chartDLQ = null
const buildChartDLQ = (data) => {
	if (!m_chartDLQ) {
		m_chartDLQ = echarts.init(document.querySelector('.dlq'));
	}
	if(!data) {
		proxy.$modal.msgWarning('没有断路器曲线数据，不能生成曲线！');
	}
	// 设置图表参数
	const option = setChartOptions(data, '(b)断路器', 'DLQ');
	m_chartDLQ.clear();
	m_chartDLQ.setOption(option, true);
}
//隔离开关
let m_chartGLKG = null
const buildChartGLKG = (data) => {
	if (!m_chartGLKG) {
		m_chartGLKG = echarts.init(document.querySelector('.glkg'));
	}
	if(!data) {
		proxy.$modal.msgWarning('没有隔离开关曲线数据，不能生成曲线！');
	}
	// 设置图表参数
	const option = setChartOptions(data, '(c)隔离开关', 'GLKG');
	m_chartGLKG.clear();
	m_chartGLKG.setOption(option, true);
}
//避雷器
let m_chartBLQ = null
const buildChartBLQ = (data) => {
	if (!m_chartBLQ) {
		m_chartBLQ = echarts.init(document.querySelector('.blq'));
	}
	if(!data) {
		proxy.$modal.msgWarning('没有避雷器曲线数据，不能生成曲线！');
	}
	// 设置图表参数
	const option = setChartOptions(data, '(d)避雷器', 'BLQ');
	m_chartBLQ.clear();
	m_chartBLQ.setOption(option, true);
}
//电流互感器
let m_chartDLHGQ = null
const buildChartDLHGQ = (data) => {
	if (!m_chartDLHGQ) {
		m_chartDLHGQ = echarts.init(document.querySelector('.dlhgq'));
	}
	if(!data) {
		proxy.$modal.msgWarning('没有电流互感器曲线数据，不能生成曲线！');
	}
	// 设置图表参数
	const option = setChartOptions(data, '(e)电流互感器', 'DLHGQ');
	m_chartDLHGQ.clear();
	m_chartDLHGQ.setOption(option, true);
}
//电压互感器
let m_chartDYHGQ = null
const buildChartDYHGQ = (data) => {
	if (!m_chartDYHGQ) {
		m_chartDYHGQ = echarts.init(document.querySelector('.dyhgq'))
	}
	if(!data) {
		proxy.$modal.msgWarning('没有电压互感器曲线数据，不能生成曲线！');
	}
	// 设置图表参数
	const option = setChartOptions(data, '(f)电压互感器', 'DYHGQ');
	m_chartDYHGQ.clear();
	m_chartDYHGQ.setOption(option, true);
}

//各类设备破坏概率的拟合曲线对比及概率密度分布曲线对比如图二和图三所示
// 各类高压电气设备破坏概率曲线对比图
let p2 = null
const buildChartP2 = (data) => {
	if (!p2) {
		p2 = echarts.init(document.querySelector('.p2'))
	}
	const xAxisData = Object.keys(data.threadMap.DYHGQ)
	const lineData1 = Object.values(data.threadMap.BYQ) //
	const lineData2 = Object.values(data.threadMap.DLQ)
	const lineData3 = Object.values(data.threadMap.GLKG)
	const lineData4 = Object.values(data.threadMap.BLQ)
	const lineData5 = Object.values(data.threadMap.DLHGQ)
	const lineData6 = Object.values(data.threadMap.DYHGQ)
	const option = {
		title: {
			bottom: 0,
			left: 'center',
			text: '图2  各类高压电气设备破坏概率曲线对比图',
			textStyle: {
				fontWeight: 'normal',
				fontSize: 18
			}
		},
		tooltip: {
			trigger: 'axis'
		},
		legend: {
			// data: ['变压器', '断路器', '隔离开关', '避雷器', 'CT', 'PT',]
		},
		color: ['#ec5851', '#415ea8', '#232120', '#9c58a2', '#ac5952', '#5cc5d4'],
		grid: {
			left: '3%',
			right: '4%',
			bottom: '6%',
			containLabel: true
		},
		//在option下添加toolbox，在feature中添加saveAsImage，这就是下载的功能
		toolbox: {
			feature: {
				// saveAsImage: {}
			}
		},
		xAxis: {
			type: 'category',
			boundaryGap: false,
			data: xAxisData
		},
		yAxis: {
			type: 'value'
		},
		series: [
			{
				name: '变压器',
				type: 'line',
				// stack: 'Total',
				smooth: true,
				data: lineData1
			},
			{
				name: '断路器',
				type: 'line',
				// stack: 'Total',
				smooth: true,
				data: lineData2
			},
			{
				name: '隔离开关',
				type: 'line',
				// stack: 'Total',
				smooth: true,
				data: lineData3
			},
			{
				name: '避雷器',
				type: 'line',
				// stack: 'Total',
				smooth: true,
				data: lineData4
			},
			{
				name: 'CT',
				type: 'line',
				//stack: 'Total',
				smooth: true,
				data: lineData5
			},
			{
				name: 'PT',
				type: 'line',
				//stack: 'Total',
				smooth: true,
				data: lineData6
			}
		]
	};
	p2.clear()
	p2.setOption(option, true)
}
//各类高压电气设备破坏概率密度曲线对比图
let p3 = null
const buildChartP3 = (data) => {
	if (!p3) {
		p3 = echarts.init(document.querySelector('.p3'))
	}
	const xAxisData = Object.keys(data.threadMap.DYHGQ);
	const lineData1 = Object.values(data.threadMap.BYQ); //变压器
	const lineData2 = Object.values(data.threadMap.DLQ); //隔离开关
	const lineData3 = Object.values(data.threadMap.GLKG); //隔離開關
	const lineData4 = Object.values(data.threadMap.BLQ); //避雷器
	const lineData5 = Object.values(data.threadMap.DLHGQ); //CT
	const lineData6 = Object.values(data.threadMap.DYHGQ); //PT
	const option = {
		title: {
			bottom: 0,
			left: 'center',
			text: '图3  各类高压电气设备破坏概率密度曲线对比图',
			textStyle: {
				fontWeight: 'normal',
				fontSize: 18
			}
		},
		tooltip: {
			trigger: 'axis'
		},
		legend: {
			// data: ['变压器', '断路器', '隔离开关', '避雷器', 'CT', 'PT',]
		},
		color: ['#ec5851', '#415ea8', '#232120', '#9c58a2', '#ac5952', '#5cc5d4'],
		grid: {
			left: '3%',
			right: '4%',
			bottom: '6%',
			containLabel: true
		},
		toolbox: {
			feature: {
				//saveAsImage: {}
			}
		},
		xAxis: {
			type: 'category',
			boundaryGap: false,
			data: xAxisData
		},
		yAxis: {
			type: 'value'
		},
		series: [
			{
				name: '变压器',
				type: 'line',
				// stack: 'Total',
				smooth: true,
				data: lineData1
			},
			{
				name: '断路器',
				type: 'line',
				// stack: 'Total',
				smooth: true,
				data: lineData2
			},
			{
				name: '隔离开关',
				type: 'line',
				// stack: 'Total',
				smooth: true,
				data: lineData3
			},
			{
				name: '避雷器',
				type: 'line',
				// stack: 'Total',
				smooth: true,
				data: lineData4
			},
			{
				name: 'CT',
				type: 'line',
				//stack: 'Total',
				smooth: true,
				data: lineData5
			},
			{
				name: 'PT',
				type: 'line',
				//stack: 'Total',
				smooth: true,
				data: lineData6
			}
		]
	};
	p3.clear()
	p3.setOption(option, true)
}

const showChart= ref(false);
//生成曲线接口
const buildChartLine = () => {
	if(tableData2.value && tableData2.value.length) {
		showChart.value = true;
		generateCurve({
			projectId: m_projectId,
		}).then((res) => {
			const { code, data } = res;
			if (code === 200 && data) {
				tableData.value.forEach(item=>{
					if(item.equipmentType=='变压器'){
						buildChartBYQ(data);
					}else if(item.equipmentType=='断路器'){
						buildChartDLQ(data);
					}else if(item.equipmentType=='隔离开关'){
						buildChartGLKG(data)
					}else if(item.equipmentType=='避雷器'){
						buildChartBLQ(data)
					}else if(item.equipmentType=='电流互感器'){
						buildChartDLHGQ(data)
					}else if(item.equipmentType=='电压互感器'){
						buildChartDYHGQ(data)
					}
				})
				buildChartP2(data);
				buildChartP3(data);
			} else {
				proxy.$modal.msgError("生成曲线失败！");
			}
		}).catch(err => {
			console.log(err.message);
		});
	} else {
		proxy.$modal.msgError("没有数据，不能生成曲线！");
	}
}

//表格合并行或列
const objectSpanMethod = ({
	row,
	column,
	rowIndex,
	columnIndex,
}) => {
	// 设备类型
	if (columnIndex === 0) {
		if (rowIndex % 5 === 0) {
			return {
				rowspan: 5,
				colspan: 1,
			}
		} else {
			return {
				rowspan: 0,
				colspan: 0,
			}
		}
	}
	// 楼层
	if (columnIndex === 1) {
		if (rowIndex % 5 === 0) {
			return {
				rowspan: 5,
				colspan: 1,
			}
		} else {
			return {
				rowspan: 0,
				colspan: 0,
			}
		}
	}
}

// 获取用户
function getUserInfo(userId) {
	getInfo(userId).then(response => {
		const { code, user } = response;
		if (code == 200 && user) {
			params.value.userName = user.userName;
			params.value.maintainerUnit = user.orgName;
		}
	});
};

//供电设备计算
const onCalc = (index) => {
	let query = [];
	if (tableData2.value && tableData2.value.length) {
		// 没有楼层号的设备类型
		const arr = [];
		// 判断是否每一层都有楼层号
		const isValid = tableData2.value.every(row => {
			if (row.floor) {
				query.push({
					'equipmentType':row.equipmentType,
					"u": row.u,
					"o": row.o, //阿尔法
					"floor": row.floor, //设备所在楼层
					"intensity": row.intensity, //烈度
				});
				return true;
			} else {
				arr.push(row.equipmentType);
				return false;
			}
		})
		// 没有则提示
		if (!isValid) {
			proxy.$modal.msgWarning((arr.join('、') || '设备') + '缺少所在楼层号，请设置楼层号后再计算!');
			return false;
		}
	}
	if (query && query.length) {
		proxy.$modal.loading('正在努力计算,请耐心等待！');
		caPseVulnerability(query).then((res) => {
			proxy.$modal.closeLoading();
			const { code, data } = res;
			if (code === 200 && data) {
				proxy.$modal.msgSuccess('计算完成！计算结果未保存，若需保存结果，请计算后点击提交按钮！');
				//非空判断
				if (data.length > 0) {
					data.forEach((item, index) => {
						tableData2.value[index].erf = item.erf
						tableData2.value[index].fxerf = item.fxerf
						tableData2.value[index].fxexp = item.fxexp
						tableData2.value[index].fxexpCorrect = item.fxexpCorrect
					})
				}
			} else {
				proxy.$modal.closeLoading();
				proxy.$modal.msgError('计算失败');
			}
		}).catch(err => {
			console.log(err);
		});
	} else {
		proxy.$modal.msgWarning('请设置需要计算的设备类型和设备所在楼层号后再操作!');
	}
};

//供电设备保存
const onSubmit = () => {
	proxy.$refs['queryRef'].validate((valid, fields) => {
		if (valid) {
			tableData2.value.forEach(item=>{
				if(!item.equipmentType){
					return;
				}
			})
			let query = {
				// 基础信息
				"tableParam": {
					...params.value,
					// 设备类型,多个
					equipmentType: params.value.equipmentType.join(','),
				},
				// 计算列表
				"cpVulnerabilityList": tableData2.value,
			}
			// tableData2.value.forEach(item => {
			// 	query.cpVulnerabilityList.push({
			// 		"equipmentType": item.equipmentType, //设备类型
			// 		"floor": item.floor, //设备所在楼层
			// 		"u": item.u,
			// 		"o": item.o, //阿尔法
			// 		"intensity": item.intensity, //烈度
			// 		"erf": item.erf, //erf
			// 		"fxerf": item.fxerf, //fxerf
			// 		"fxexp": item.fxexp, //fxexp
			// 		"fxexpCorrect": item.fxexp,//修正值
			// 	});
			// })
			proxy.$modal.loading('保存中,请耐心等待！');
			savePseVulnerability(query).then((res) => {
				proxy.$modal.closeLoading();
				const { code, data } = res;
				if (code === 200) {
					proxy.$modal.msgSuccess("保存成功!");
					// 延迟跳转
					setTimeout(() => {
						router.push('/lifelineVulnerAnalysis/lifelineMain')
					}, 1500)
				}
			}).catch(err => {
				proxy.$modal.closeLoading();
				console.log(err.message);
			});
		} else {
			proxy.$refs['queryRef'].scrollToField(Object.keys(fields)[0])
		}
	})
}

// 获取数据
function getData(parmas) {
	getByIdAndType(parmas).then((res) => {
		const { code, data } = res;
		if (code === 200 && data) {
			tableData2.value = [];
			const { map, tableEntity } = data;
			// 基础信息
			if (tableEntity) {
				params.value = {
					...tableEntity,
					// 设备类型,多个
					equipmentType: tableEntity.businessObject ? tableEntity.businessObject.split(',') : [],
				};
				// 维护时间
				if (tableEntity.updateTime || tableEntity.createTime) {
					const dateTime = new Date(tableEntity.updateTime || tableEntity.createTime)
					params.value.createTime = parseTime(dateTime);
				} else {
					params.value.createTime = '';
				}
				// 获取创建人信息
				if (tableEntity.createUser) {
					// 获取用户信息
					getUserInfo(tableEntity.createUser);
				}
			}
			// onChangeEquipmentType(params.value.equipmentType)

			// 计算结果
			if (map) {
				// 过滤
				const arr = [];
				const arr2 = [];
				// 遍历设备类型,处理数据回显
				for (const key in map) {
					if (map[key]) {
						// 获取楼层号
						let objItem = {};
						tableData.value.some(item => {
							if(key == item.equipmentType){
								objItem = { ...item };
							}
						})
						// 存楼层号
						let arrFloor = [];
						map[key].forEach((item) => {
							item.isEdit = false;
							item.disabled = operateType.value === 'query' ? true : false;
							arr2.push(item);
							// 获取楼层号
							if(item.floor && !arrFloor.includes(item.floor + '')) {
								arrFloor.push(item.floor + '');
							}
						});
						arr.push({
							...objItem,
							// 每类设备类型的所有楼层号
							floor: arrFloor.join(',')
						});
					}
				}
				// 表格数据加载
				tableData.value = arr;
				tableData2.value = arr2;
			}
		}
	}).catch(err => {
		console.log(err);
	});
}

//字典表查询
const optionList1 = ref([])
/** 获取字典值 */
async function getDictData() {
    await getValidDictItemsByDictCode("smxsfqk").then(response => {
        optionList1.value = response.data;//设防情况
    });

}

getDictData();

let m_projectId = null;
// 挂载
onMounted(() => {
	// 获取路由参数
	const id = route.query.id;
	m_projectId = route.query.id;
	if (id) {
		disabled.value = true;
		const parmas = { type: '7', id: id };
		// 获取数据
		getData(parmas);
	} else {
		disabled.value = false;
	}

	const isEdit = id && !route.query.operateType;
	let first = true;
	// 监听设备类型参数变化
	watch(() => tableData.value, (val, old) => {
		if (!id || (isEdit && !first)) { // 添加加载,修改初次不加载, 查询不监听
			if (val && val.length) {
				// 根据表1的数据设置表2
				setTableData2BytableData(val)
			} else {
				tableData2.value.length = 0;
			}
		}
		first = false;
	}, {
		//在侦听器创建时立即触发回调
		immediate: !isEdit,
		//强制深度遍历
		deep: true,
	})
});
</script>

<style lang="scss">
.table-wrapper {
	position: relative;

	h4 {
		font-size: 16px;
		font-weight: bold;
		color: #107ce5;
		text-align: center;
	}
}

.el-tag {
	margin: 5px;
}

.input-floor {
	.el-button {
		margin: 0 5px;
	}
	.el-input-numbe {
		margin: 0 5px!important;
	}
}

.myChart {
	margin-bottom: 30px;
}
</style>


